package com.miao.im.filter;

import com.miao.im.common.Message;
import com.miao.im.common.annotation.MessageCommand;
import com.miao.im.server.session.SessionContext;
import com.miao.im.support.exception.AuthenticationException;
import com.miao.im.support.handler.AbstractMessageHandler;
import com.miao.im.support.handler.MessageHandlerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/2 10:24
 * @Description:
 */
@Component
public class AuthMessageFilter extends AbstractMessageFilter {
    @Autowired
    private MessageHandlerFactory handlerFactory;
    @Override
    public boolean doFilter(Message message, SessionContext sessionContext) {
        AbstractMessageHandler<?> handler = handlerFactory.createHandler(message.getCommandType());
        MessageCommand annotation = handler.getClass().getAnnotation(MessageCommand.class);
        if (!annotation.needAuth()){
            return true;
        }
        if (!sessionContext.isAuth()) {
            throw new AuthenticationException("请先登录！");
        }
        return true;
    }

    @Override
    public int order() {
        return Integer.MIN_VALUE;
    }
}
